from simpy import Resource, Environment

from x_pc.core import Device, DeviceCost, System
from x_pc.model.model import Task


class CZ(Device, DeviceCost):
    """
    307 自动称重盘点区
    自称重(ZCZ)
    """
    TIME_COST = 1
    # 资源
    resource: Resource = None

    def cost(self, *args, **kwargs) -> float:
        return self.TIME_COST


class CZSystem(System):
    """
    自动称重盘点区 系统
    """
    CZ_NUMS = 1
    # CZ列表
    cz_list: list[CZ] = list()

    def __init__(self, env: Environment, name: str, code: str = None):
        super().__init__(env, name, code)
        self.__init_cz_list()

    def __init_cz_list(self):
        self.cz_list = [CZ(self.env, f'称重-{_ + 1}') for _ in range(self.CZ_NUMS)]

    def run_task(self, task: Task):
        if not self.cz_list:
            while self.running:
                yield self.env.timeout(1)
                if self.cz_list:
                    break
        #
        cz = self.cz_list.pop(0)
        with cz.resource.request() as req:
            yield req
            process = task.process
            #
            process.begin_ts = self.env.now
            #
            yield self.env.timeout(cz.cost())
            #
            process.end_ts = self.env.now
            process.device_code = cz.name
            # TODO: 根据不同的任务类型 将任务分配至不同的设备
            process.end_pos = None
        self.cz_list.append(cz)
